package eu.news.interconnect;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import eu.news.config.Debugger;

public class Communicator {

	/**
	 * 向指定URL发送Message, 并获取返回Message
	 * @param remoteUrl
	 * @param message
	 * @return Message or null
	 */
	public static Message send(String remoteUrl, Message message){
		try {
			URL url = new URL(remoteUrl);
			HttpURLConnection conn=(HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setDoOutput(true);
			conn.connect();
			conn.getOutputStream().write(message.getSerializeBytes());
			conn.getOutputStream().close();
			//获取返回的数据
			Object response = Utils.generateObject(conn.getInputStream());
			if (response instanceof Message)
				return (Message) response;
		} catch (IOException e) {
			Debugger.printStackTrace(e);
		} catch (ClassNotFoundException e) {
			Debugger.printStackTrace(e);
		} 
		return null;
	}
}
